﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyModel;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;

namespace EFLearn
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime start = DateTime.Now;
            TestContext _context = new TestContext();
            //for (int i = 0; i < 10; i++)
            //{
            //    _context.Users.Add(new Users()
            //    {
            //        Name = $"User{ i }"
            //    });
            //    _context.SaveChanges();
            //}
            //Console.WriteLine(_context.Users.Count());


            using (TestContext context = new TestContext())
            {
                var sss = context.Set<Users>().FirstOrDefaultAsync(r => r.Name == "User6").Result;
            }



            Console.WriteLine("总时间,秒数：" + (DateTime.Now - start).TotalSeconds);
        }
    }



    public class TestContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //注入Sql链接字符串
            optionsBuilder.UseSqlServer(@"Database=DDD;User ID=sa;Password=111111;Server=.;");
        }

        // protected override void OnModelCreating(DbModelBuilder modelBuilder)

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            Type type = null;
            try
            {
                System.Collections.Generic.IEnumerable<CompilationLibrary> compilationLibrary = DependencyContext
                    .Default
                    .CompileLibraries
                    .Where(x => !x.Serviceable && x.Type != "package");
                foreach (var _compilation in compilationLibrary)
                {
                    AssemblyLoadContext.Default
                    .LoadFromAssemblyName(new AssemblyName(_compilation.Name))
                    .GetTypes()
                    .Where(x => x.GetTypeInfo().BaseType != null && x.BaseType == (typeof(BaseEntity)))
                    .ToList().ForEach(t =>
                    {
                        type = t;
                        modelBuilder.Model.AddEntityType(t);
                    });
                }
                base.OnModelCreating(modelBuilder);
            }
            catch (Exception ex)
            {

            }
        }
    }


    public class BaseEntity { }

    [Table("Users")]
    public class Users : BaseEntity
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
    }

}
